package com.ruoyi.luban.controller;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableDataInfo2;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.luban.domain.*;
import com.ruoyi.luban.domain.dto.CreateOrderDto;
import com.ruoyi.luban.domain.dto.FindOrderDto;
import com.ruoyi.luban.domain.dto.UpdateOrderDto;
import com.ruoyi.luban.domain.vo.DealerOrderVo;
import com.ruoyi.luban.domain.vo.LoginUserAndTokenVo;
import com.ruoyi.luban.domain.vo.OrderVo;
import com.ruoyi.luban.service.IPDealerService;
import com.ruoyi.luban.service.IPFileInfoService;
import com.ruoyi.luban.service.IPOrderService;
import com.ruoyi.luban.service.IPWxLoginUserService;
import com.ruoyi.luban.service.impl.PDealerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 订单Controller
 * 
 * @author ruoyi
 * @date 2024-01-28
 */
@RestController
@RequestMapping("/order")
public class POrderController extends WXBaseController
{
    @Autowired
    private IPOrderService pOrderService;
    @Autowired
    private IPFileInfoService fileInfoService;
    @Autowired
    private IPWxLoginUserService ipWxLoginUserService;

    /**
     * 删除订单
     */
    @Log(title = "删除订单", businessType = BusinessType.INSERT)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids,@RequestHeader(value = "token",defaultValue = "test")  String token)
    {
        WXUserLoginInfo info = this.getLoginUserInfo(token);
        if (info == null){
            return error("登录失效！");
        }
        return toAjax(pOrderService.deletePOrderByIds(ids));
    }

    /**
     * 新增订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("addOrder")
    public AjaxResult addOrder(@RequestBody CreateOrderDto pOrder, @RequestHeader(value = "token",defaultValue = "test")  String token)
    {
        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info == null){
            return error_to_login();
//            return error("登录失效！");
        }
//        Long schoolId = info.getSchoolId();
        return pOrderService.createOrder(info, pOrder);
//        if(schoolId == null){
//            setLoginUserInfo2(info);
//        }
//        return toAjax(order);
    }

    /**
     * 准备报价
     */
    @Log(title = "准备报价", businessType = BusinessType.INSERT)
    @PostMapping("updatePrice")
    public AjaxResult updatePrice(@RequestBody UpdateOrderDto pOrder, @RequestHeader(value = "token",defaultValue = "test")  String token)
    {
        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info == null){
            return error_to_login();
//            return error("登录失效！");
        }
        return pOrderService.updatePrice(info,pOrder);
//        return toAjax(pOrderService.updatePrice(info,pOrder));
    }
    /**
     * 同意报价
     */
    @Log(title = "订单同意报价", businessType = BusinessType.INSERT)
    @PostMapping("agreePrice")
    public AjaxResult agreePrice(@RequestBody UpdateOrderDto pOrder, @RequestHeader(value = "token",defaultValue = "test")  String token)
    {
        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info == null){
            return error_to_login();
//            return error("登录失效！");
        }
        return pOrderService.agreePrice(info,pOrder);
//        return toAjax(pOrderService.agreePrice(info,pOrder));
    }

    /**
     * 完成订单
     */
    @Log(title = "完成订单", businessType = BusinessType.INSERT)
    @PostMapping("completeOrder")
    public AjaxResult completeOrder(@RequestBody UpdateOrderDto pOrder, @RequestHeader(value = "token",defaultValue = "test")  String token)
    {
        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info == null){
            return error_to_login();
//            return error("登录失效！");
        }
        return pOrderService.completeOrder(info,pOrder);
//        return toAjax(pOrderService.completeOrder(info,pOrder));
    }
    /**
     * 验收订单
     */
    @Log(title = "验收订单", businessType = BusinessType.INSERT)
    @PostMapping("checkOrder")
    public AjaxResult checkOrder(@RequestBody UpdateOrderDto pOrder, @RequestHeader(value = "token",defaultValue = "test")  String token)
    {
        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info == null){
            return error_to_login();
//            return error("登录失效！");
        }
        return pOrderService.checkOrder(info,pOrder);
//        return toAjax(pOrderService.checkOrder(info,pOrder));
    }

    /**
     * 获取订单详细信息
     */
    @GetMapping(value = "/getOrderInfo/{id}")
    @Log(title = "获取订单详细信息", businessType = BusinessType.INSERT)
    public AjaxResult getOrderInfo(@PathVariable("id") Long id,@RequestHeader(value = "token",defaultValue = "test")  String token)
    {
        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info == null){
            return error_to_login();
//            return error("登录失效！");
        }
        return success(pOrderService.getOrderInfo(id));
    }


    /**
     * 查询订单列表
     */
    @GetMapping("/listByLoginUser")
    @Log(title = "查询登录用户订单列表", businessType = BusinessType.INSERT)
    public TableDataInfo2 listByLoginUser(FindOrderDto pOrder, @RequestHeader(value = "token",defaultValue = "test")  String token)
    {

        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info != null) {
            //判断是否学校身份
            if ("1".equals(info.getLoginType()))  {
                //获取登录用户
                PWxLoginUser pWxLoginUser = ipWxLoginUserService.selectPWxLoginUserById(info.getLoginUser().getLoginUserId());
                pOrder.setDealerId(pWxLoginUser.getContactId());
            }else{
                pOrder.setUserId(info.getLoginUser().getLoginUserId());
            }
        }
        startPage();

        List<POrder> list = pOrderService.selectPOrderList(info,pOrder);
        List<OrderVo> orderList = new ArrayList<>();
        if(list != null && list.size() > 0) {
            orderList = JSONObject.parseArray(JSONObject.toJSONString(list),OrderVo.class);
            long[] longs = orderList.stream().mapToLong(POrder::getId).toArray();
            List<PFileInfo> fileInfos = fileInfoService.selectPFileInfoListByContactIds(longs);
            if(fileInfos.size() >0){
                List<OrderVo> finalOrderList = orderList;
                fileInfos.stream().forEach(bean ->{
                    finalOrderList.stream().forEach(bean2 ->{
                        if(bean.getContactId() == bean2.getId()){
                            bean2.setFileUrl(bean.getFileUrl());
                        }
                    });
                });
                orderList = finalOrderList;

            }
        }

        PageDomain pageDomain = TableSupport.buildPageRequest();
        pOrder.setOrderByColumn(pageDomain.getOrderByColumn());
        pOrder.setIsAsc(pageDomain.getIsAsc());
        Integer count = pageDomain.getPageNum() * pageDomain.getPageSize();
        String selectPOrderListSum = pOrderService.selectPOrderListSum(info,pOrder,count);


        TableDataInfo2 tableDataInfo2 = getDataTable2(orderList);
        if(selectPOrderListSum == null){
            selectPOrderListSum = "0.00";
        }
        tableDataInfo2.setTatalPrice(selectPOrderListSum);
        return tableDataInfo2;
    }
    /**
     * 查询订单统计
     */
    @GetMapping("/dealerOrders")
    @Log(title = "查询登录用户订单列表", businessType = BusinessType.INSERT)
    public AjaxResult dealerOrders(@RequestHeader(value = "token",defaultValue = "test")  String token)
    {

        LoginUserAndTokenVo info = this.getLoginUserInfo2(token);
        if (info == null){
            return error_to_login();
//            return null;
        }
        return success(pOrderService.dealerOrders(info));
    }
}
